package com.eqxiu.ieditor.api.controller.mall;


import com.eqxiu.common.utils.StringUtils;
import com.eqxiu.ieditor.api.controller.BaseApiController;
import com.eqxiu.ieditor.api.controller.BaseController;
import com.eqxiu.ieditor.commons.web.ResultData;
import com.eqxiu.mall.search.api.IMallSearchServiceApi;
import com.eqxiu.mall.search.dto.FiltersDTO;
import com.eqxiu.mall.search.dto.OrdersDTO;
import com.eqxiu.mall.search.dto.RecommendDTO;
import com.eqxiu.mall.search.dto.UserInfoDTO;
import com.eqxiu.mall.search.enumeration.SearchApiCodeEnum;
import com.eqxiu.tiny.pagination.PageDTO;
import com.google.gson.Gson;
import eqxiu.mall.product.dto.ProductDTO;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/api/wap/index")
@Api(description = "商城-各首页搜索Controller")

public class WapIndexSearchController extends BaseController implements BaseApiController {
    Logger logger = LoggerFactory.getLogger(WapIndexSearchController.class);

    @Autowired
    private IMallSearchServiceApi mallSearchServiceApi;

    @Value("${redis.timeOut}")
    private Integer redisTimeOut;

    // h5一级分类
    @Value("${h5.back.first.id}")
    private Integer h5FirstCategory;
    // 长页一级分类
    @Value("${longpage.back.first.id}")
    private Integer longPageFirstCategory;
    //易表单一季分类
    @Value("${form.back.first.id}")
    private Integer formFirstCategory;
    //互动一级分类
    @Value("${interacth5.back.first.id}")
    private Integer gcFirstCategory;
    //请设计后端一级分类
    @Value("${design.back.first.id}")
    private Integer designFirstCategory;
    //视频后端一级分类
    @Value("${video.back.first.id}")
    private Integer videoFirstCategory;




        /**
         * 获取精选模板
         * @param request
         * @return
         */
        @PostMapping("/choiceProducts")
        @ResponseBody
        public ResultData choiceProducts(HttpServletRequest request, String searchCode,String positionId, String category,Integer pageNo, Integer pageSize) {
            //判断用户是否登录
            String userId = geUserId(request);
            Map map = new HashMap();
            if(StringUtils.isEmpty(userId)){
                //未登录获取精选分类商品
                com.eqxiu.tiny.pagination.PageDTO<ProductDTO> pagelist = PageDTO.create(null, 0, pageNo, pageSize);
                // 精选模板获取默认全局sort前6个
                UserInfoDTO userInfoDTO = new UserInfoDTO();
                userInfoDTO.setIp(this.getIpAddr(request));
                userInfoDTO.setUid(geUserId(request));
                //过滤条件
                List<FiltersDTO> filtersDTOList = new ArrayList<FiltersDTO>();
                //排序
                List<OrdersDTO> ordersDTOList = new ArrayList<OrdersDTO>();
                dealFilter(searchCode,filtersDTOList,ordersDTOList,category,"eqs_sort");
                //调用商城新search
                logger.info("获取首页精选模板入参" + new Gson().toJson(filtersDTOList));
                pagelist = mallSearchServiceApi.search(searchCode, userInfoDTO, "", filtersDTOList, ordersDTOList,pageNo, pageSize);
                logger.info("获取首页精选模板返回" + new Gson().toJson(pagelist));
                map.put("total",pagelist.getTotal());
                map.put("dataList",pagelist.getDataList());
                return success().setMap(map);
            }else{
                //登录获取推荐商品
                return success().setMap(recommondProduct(request,positionId,pageNo,pageSize));
            }

        }


    /**
     * 获取推荐商品
     * @param request
     * @param positionId
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Map recommondProduct(HttpServletRequest request, String positionId, Integer pageNo, Integer pageSize){
        Map map = new HashMap();
        Map<String, Object> extra = new HashMap<>(16);
        RecommendDTO recommendDTO = new RecommendDTO();
        recommendDTO.setUserId(this.geUserId(request));
        recommendDTO.setIp(this.getIpAddr(request));
        recommendDTO.setPositionId(positionId);
        extra.put("size", pageSize);
        extra.put("page", pageNo);
        recommendDTO.setExtra(extra);
        logger.info("this is recommend request={}", new Gson().toJson(recommendDTO));
        PageDTO<ProductDTO> recommendDTOs = mallSearchServiceApi.searchTemplateRec(recommendDTO);
        logger.info("this is recommend dto={}", new Gson().toJson(recommendDTOs));
        map.put("total",recommendDTOs.getTotal());
        map.put("dataList",recommendDTOs.getDataList());
        return map;
    }

    @PostMapping("/newRecommondProducts")
    @ResponseBody
    public ResultData newRecommondProducts(HttpServletRequest request, String searchCode,Integer type,Integer pageNo, Integer pageSize) {
        // 精选模板获取默认全局sort前6个
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        userInfoDTO.setIp(this.getIpAddr(request));
        userInfoDTO.setUid(geUserId(request));
        //过滤条件
        List<FiltersDTO> filtersDTOList = new ArrayList<FiltersDTO>();
        //排序
        List<OrdersDTO> ordersDTOList = new ArrayList<OrdersDTO>();
        //0-首页，1-h5,2-长页，3-易表单，4-互动，5-请设计，6-视频
        Integer category = null;
        if(1==type){
            category = h5FirstCategory;
        }else if(2==type){
            category = longPageFirstCategory;
        }else if(3==type){
            category = formFirstCategory;
        }else if(4==type){
            category = gcFirstCategory;
        }else if(5==type){
            category = designFirstCategory;
        }else if(6==type){
            category = videoFirstCategory;
        }
        String categoryStr = category+"";
        dealFilter(searchCode,filtersDTOList,ordersDTOList,categoryStr,"create_time");
        //调用商城新search
        logger.info("this is recommend request={}", new Gson().toJson(filtersDTOList));
        PageDTO<ProductDTO> resultMap = mallSearchServiceApi.search(searchCode, userInfoDTO, "", filtersDTOList, ordersDTOList,pageNo, pageSize);
        logger.info("获取首页精选模板返回={}" + new Gson().toJson(resultMap));
        return success().setList(resultMap.getDataList());
    }

        public void dealFilter(String searchCode,List<FiltersDTO> filtersDTOList,List<OrdersDTO> ordersDTOList,String category,String orderField){
            //分类过滤
            if (StringUtils.isNotBlank(category)) {
                FiltersDTO filtersDTO = new FiltersDTO();
                filtersDTO.setComparator("equals");
                filtersDTO.setField("navigator_ids");
                filtersDTO.setValue(category);
                filtersDTOList.add(filtersDTO);
            }
            //h5取app,长页易表单互动不加
            if(searchCode.equals(SearchApiCodeEnum.WAP_H5_SEARCH.code()) ||searchCode.equals(SearchApiCodeEnum.WAP_VIDEO_SEARCH.code()) ){
                FiltersDTO osTypeFilterDTO = new FiltersDTO();
                osTypeFilterDTO.setValue("2");
                osTypeFilterDTO.setField("os_type");
                osTypeFilterDTO.setComparator("equals");
                filtersDTOList.add(osTypeFilterDTO);
            }

            OrdersDTO ordersDTO = new OrdersDTO();
            ordersDTO.setField(orderField);
            ordersDTO.setOrder("desc");
            ordersDTOList.add(ordersDTO);
        }


    }
